package com.github.wxhnyfy.enums;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 工具类型
 *
 * @author chenwc
 */
public enum ToolType {
    EASY_EXCEL(0, "EasyExcel"),
    FAST_EXCEL(1, "FastExcel"),
    APACHE_POI_EXCEL(2, "ApachePoiExcel");

    private static final Logger logger = LoggerFactory.getLogger(ToolType.class);

    private String toolName;

    private Integer code;

    ToolType(int code, String toolName) {
        this.code = code;
        this.toolName = toolName;
    }

    /**
     * 获取工具类型
     * 读取命令行参数-Dexcel.tool.type的值，如果为空则默认为FAST_EXCEL
     *
     * @return 工具类型
     */
    public static ToolType getToolType() {
        String toolType = System.getProperty("excel.tool.type");
        ToolType toolTypeEnum = null;
        if (StringUtils.isEmpty(toolType)) {
            toolTypeEnum = FAST_EXCEL;
        }
        else {
            try {
                int code = Integer.parseInt(toolType);
                toolTypeEnum = getToolType(code);
            } catch (Exception e) {
                toolTypeEnum = getToolType(toolType);
            }
        }
        if (toolTypeEnum == null) {
            logger.error("未知工具类型: " + toolType);
            throw new RuntimeException("未知工具类型: " + toolType);
        }
        logger.info("Excel Tool 类型为：{}", toolTypeEnum.getToolName());
        return toolTypeEnum;
    }

    /**
     * 根据code获取工具类型
     *
     * @param code 代码
     * @return 工具类型
     */
    public static ToolType getToolType(Integer code) {
        for (ToolType toolType : ToolType.values()) {
            if (toolType.getCode().equals(code)) {
                return toolType;
            }
        }
        return null;
    }

    /**
     * 根据工具名称获取工具类型
     *
     * @param toolName 工具名称
     * @return 工具类型
     */
    public static ToolType getToolType(String toolName) {
        for (ToolType toolType : ToolType.values()) {
            if (toolType.getToolName().equals(toolName)) {
                return toolType;
            }
        }
        return null;
    }

    public String getToolName() {
        return toolName;
    }

    public void setToolName(String toolName) {
        this.toolName = toolName;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}
